package com.ruoyi.project.emr.controller;

import java.util.List;
import java.util.Map;

import com.ruoyi.project.emr.domain.EmrPrescription;
import com.ruoyi.project.emr.domain.EmrRecordInfo;
import com.ruoyi.project.emr.service.IEmrMedicalRecordService;
import com.ruoyi.project.emr.service.IEmrPrescriptionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;

/**
 * 开具处方Controller
 *
 * @author gzu
 * @date 2023-07-22
 */
@RestController
@RequestMapping("/emr/add_prescription")
public class EmrAddPrescriptionController extends BaseController
{
    @Autowired
    private IEmrPrescriptionService emrPrescriptionService;

    @Autowired
    private IEmrMedicalRecordService recordService;

    /**
     * 查询病历的关联信息
     * @param recordInfo
     * @return
     */
    @GetMapping("/record_info")
    public TableDataInfo getRecordInfo(EmrRecordInfo recordInfo) {
        startPage();
        List<EmrRecordInfo> list = recordService.selectRecordInfo(recordInfo);
        return getDataTable(list);
    }

    /**
     * 新增开具处方并返回生成的处方信息
     */
    @Log(title = "开具处方", businessType = BusinessType.INSERT)
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public AjaxResult add(@RequestBody EmrPrescription emrPrescription)
    {
        int id = emrPrescriptionService.insertEmrPrescription(emrPrescription);
        String recordId = emrPrescription.getMedicalRecordId();

        return success(emrPrescriptionService.getLatestPrescription(recordId));
    }

    /**
     * 往处方中添加药品
     */
    @Log(title = "往处方中添加药品", businessType = BusinessType.INSERT)
    @RequestMapping(value = "/save_drugs", method = RequestMethod.POST)
    public AjaxResult addDrugs(@RequestBody Map<String, Object> params) {
        System.err.println("save_drugs");
        Object preId = params.get("prescriptionId");
        if (preId == null) {
            return error("bad request body");
        }
        Object drugId = params.get("drugId");
        if (drugId == null) {
            return error("bad request body");
        }
        Object count = params.get("count");
        if (count == null) {
            return error("bad request body");
        }

        return toAjax(emrPrescriptionService.insertDrugsToPrescription(
                (Integer)preId,
                (Integer)drugId,
                (Integer)count
        ));
    }
}
